<template>
    <div class="console-page forbid-select">
        <div style="display: flex;height: 100%;">
            <div style="width: 70%;height: 100%;">
                <c_calendar v-model="date" class="calendar" ref="calendarRef" @change="change">
                    <template #default="{ day }">
                        <div class="dayNumber" style="position: relative;">
                            <div class="dayinfo">
                                <div>
                                    {{ day.day }}
                                </div>
                                <div :class="getDayItemClass(day)">
                                    {{ showDayInfo(day) }}
                                </div>
                            </div>
                            <div :class="getHolidayClass(day)">
                                {{ holiday(day) }}
                            </div>
                            <div v-if="checkEvent(day.date)" class="show-event-item" />
                        </div>
                    </template>
                </c_calendar>
            </div>
            <div style="width:30%">
                <div style="height: 40%; margin-left: 3px;display: flex;background: rgba(157,157,0,.5);">
                    <el-scrollbar class="full-percent">
                        <div class="calendar-detail">
                            <div class="calendar-row" style="height: 75%;">
                                <div class="calendar-item no-wrap">{{ currentDayInfo.date }}</div>
                                <div class="calendar-item no-wrap">{{ weekDay[currentDayInfo.weekday - 1] }}</div>
                                <div class="calendar-item no-wrap">
                                    {{ (currentDayInfo.lunarcalendar || "").replace("卅", "三十").replace("廿", "二十") }}
                                </div>
                                <div class="calendar-item no-wrap">{{ currentDayInfo.yeartips }}年</div>
                                <div class="calendar-item no-wrap">{{ currentDayInfo.monthtips }}月</div>
                                <div class="calendar-item no-wrap">{{ currentDayInfo.daytips }}日</div>
                                <div class="calendar-item no-wrap">生肖{{ currentDayInfo.chinesezodiac }}</div>
                                <div class="calendar-item no-wrap">{{ currentDayInfo.constellation }}</div>
                                <div class="calendar-item no-wrap">{{ currentDayInfo.solarterms }}</div>
                                <div class="calendar-item no-wrap">年第{{ currentDayInfo.dayofyear }}天</div>
                                <div class="calendar-item no-wrap">年第{{ currentDayInfo.weekofyear }}周</div>
                                <div class="calendar-item no-wrap">月第{{ currentDayInfo.weekinmonth }}周</div>
                                <div class="calendar-item no-wrap" v-if="currentDayInfo.typedes">
                                    {{ currentDayInfo.indexworkdayofmonth ? "月第" + currentDayInfo.indexworkdayofmonth +
                                        "个工作日" : currentDayInfo.type === 2 ? currentDayInfo.typedes : "休息日" }}
                                </div>
                                <div class="calendar-item no-wrap" v-else>
                                    暂无节假日信息
                                </div>
                                <div class="calendar-item" style="color: #005cd3;width: calc(75% - 24px);"
                                    v-if="currentDayInfo.holidaydes">
                                    距离下个节日{{ currentDayInfo.recentholidaydes }}{{ currentDayInfo.recentholiday
                                    }},还剩{{ currentDayInfo.recentholidays }}天
                                </div>
                                <div class="calendar-item" style="color: #005cd3;width: calc(75% - 24px);" v-else>
                                    暂无下一个节假日信息
                                </div>

                            </div>
                            <div class="calendar-row" style="height: 25%;">
                                <div class="calendar-item2" style="color: #d11313;">忌：{{ currentDayInfo.avoid }}
                                </div>
                                <div class="calendar-item2" style="color: #00a92e;">宜：{{ currentDayInfo.suit }}
                                </div>
                            </div>
                        </div>
                    </el-scrollbar>
                </div>
                <div style="height: 60%;margin-left: 3px;background: rgba(255, 255, 255, .3);position: relative;">
                    <el-scrollbar class="full-percent event">
                        <div style="background: rgba(255, 255, 255, .3);height: 100%;">
                            <div v-if="!calendarEventShow.length" class="empty-event">暂无代办事项</div>
                            <div v-else style="display: flex;flex-wrap: wrap;">
                                <div v-for="(item, index) in calendarEventShow" :key="index" class="font-auto-resize"
                                    style="display: flex;width: 100%;" @dblclick="editEvent(item)">
                                    <div class="event-item-inner">
                                        <div>{{ index + 1 }}:</div>
                                        <div style="padding-left: 5px;">{{ item.title }}</div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </el-scrollbar>
                    <el-button class="button-auto-resize" :icon="getIcon('plus')" circle
                        style="position: absolute;right: 3px;bottom: 3px;" @click="showDrawer = true" />
                </div>
            </div>
        </div>
        <el-dialog :show-close="false" v-model="showDrawer" :close-on-click-modal="false" append-to-body @open="open"
            @closed="close" class="forbid-select calendar-dialog">
            <template #header>
                <div class="font-auto-resize" style="text-align: center;">{{ date.format("YYYY-MM-DD") }}</div>
            </template>
            <el-form inline :model="eventDetail" class="form-item form-auto-resize" spellcheck="false" :rules="rules"
                ref="eventRef" @submit.native.prevent>
                <el-form-item label="事项名称" prop="title">
                    <el-input class="input-auto-resize" v-model=eventDetail.title />
                </el-form-item>
                <el-form-item label="开始时间" prop="startTime">
                    <el-time-picker class="input-auto-resize" v-model="eventDetail.startTime" :editable="false"
                        placeholder="开始时间为空不进行提醒" popper-class="time-picker" :teleported="false"
                        value-format="HH:mm:ss" />
                </el-form-item>
                <el-form-item label="事项内容">
                    <el-input class="font-auto-resize" v-model=eventDetail.content type="textarea" resize="none"
                        rows="10" />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button class="fit-auto-resize" type="danger" @click="deleteEvent"
                    style="position: absolute;left: 10px;" v-if="eventDetail.sequence">删除</el-button>
                <el-button class="fit-auto-resize" type="info" @click="showDrawer = false">取消</el-button>
                <el-button class="fit-auto-resize" type="primary" @click="commitEvent">
                    {{ eventDetail.sequence ? "修改" : "添加" }}
                </el-button>
            </template>
        </el-dialog>

    </div>
</template>

<script setup>
import { getIcon } from "@/utils/tools"
import { useElMessage, useModalSize, useRequest, useElLoading } from "@usehook"
import { apiPrefix } from "@/utils/constant"

let date = $ref(new Date())
let calendarInfo = $ref({})
let calendarEvent = $ref({})

let showDrawer = $ref(false)
const rules = {
    title: [{
        required: true,
        message: "请输入事项名称",
        trigger: []
    }]
}

const calendarEventShow = $computed(() => {
    return calendarEvent[date.format("YYYY-MM-DD")] || []
})

const eventRef = $ref(null)
let eventDetail = $ref({ startTime: "" })
const open = () => {
    useModalSize()
}
const close = () => {
    useModalSize(false)
    eventDetail = { startTime: "" }
    eventRef.clearValidate()
}

const editEvent = (item) => {
    eventDetail = { ...item }
    showDrawer = true
}
const commitEvent = () => {
    eventRef.validate((pass) => {
        if (pass) {
            eventDetail.day = date.format("YYYY-MM-DD")
            const useloading = useElLoading({ text: "正在提交事项内容" })
            useRequest({ url: "/calendar/save", method: "post", ...eventDetail }).then(resData => {
                console.log(resData)
                if (resData && resData.status) {
                    getCalendarEvent()
                    useElMessage("事项添加成功")
                }
            }).finally(() => {
                showDrawer = false
                useloading.close()
            })
        }
    })
}

const deleteEvent = () => {
    useRequest({ url: "/calendar/delete", method: "post", sequence: eventDetail.sequence }).then(resData => {
        if (resData && resData.status) {
            getCalendarEvent()
            useElMessage("事项删除成功")
        }
    }).finally(() => {
        showDrawer = false
    })
}

const checkEvent = (day) => {
    return !!calendarEvent[day.format("YYYY-MM-DD")]
}

const getCalendarEvent = () => {
    const _calendarEvent = {}
    useRequest({ url: "/calendar/getCalendar" }).then(resData => {
        if (resData && resData.status) {
            for (let event of resData.data) {
                if (_calendarEvent[event.day] && _calendarEvent[event.day].length) {
                    _calendarEvent[event.day].push(event)
                } else {
                    _calendarEvent[event.day] = [event]
                }
            }
            calendarEvent = { ..._calendarEvent }
        }
    })
}

const change = (day) => {
    if (day.getMonth() <= 1 && !calendarInfo[new Date(day.getFullYear(), day.getMonth() - 1, day.getDate()).format("YYYY-MM-DD")]) {
        getCalendar(day.getFullYear() - 1)
    } else if (day.getMonth() >= 11 && !calendarInfo[new Date(day.getFullYear(), day.getMonth() + 1, day.getDate()).format("YYYY-MM-DD")]) {
        getCalendar(day.getFullYear() + 1)
    }
}

const weekDay = ["星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日"]

const getCalendar = (year) => {
    useRequest({ url: apiPrefix + "/calendar?year=" + year }).then(resData => {
        for (let dayInfo of resData.data || []) {
            calendarInfo[dayInfo.date] = dayInfo
        }
    })
}

const currentDayInfo = $computed(() => {
    return calendarInfo[date.format("YYYY-MM-DD")] || {}
})

const showDayInfo = (day) => {
    const info = calendarInfo[day.date.format("YYYY-MM-DD")] || {}
    if (info.solarfestival) {
        return info.solarfestival
    } else if (info.lunarfestival) {
        return info.lunarfestival
    } else if (info.solarterms && !info.solarterms.endsWith("后")) {
        return info.solarterms
    } else {
        let lunarcalendar = info.lunarcalendar || ""
        let newLunarcalendar = lunarcalendar.replace("卅", "三十").replace("廿", "二十").replace(/([一二三四五六七八九十腊]+月)/g, "")
        return newLunarcalendar === "初一" ? lunarcalendar.replace(newLunarcalendar, "") : newLunarcalendar
    }
}

const getDayItemClass = (day) => {
    const info = calendarInfo[day.date.format("YYYY-MM-DD")] || {}
    if (info.solarfestival) {
        return "solarfestival"
    } else if (info.lunarfestival) {
        return "lunarfestival"
    } else if (info.solarterms && !info.solarterms.endsWith("后")) {
        return "solarterms"
    } else {
        let lunarcalendar = info.lunarcalendar || ""
        let newLunarcalendar = lunarcalendar.replace("卅", "三十").replace("廿", "二十").replace(/([一二三四五六七八九十腊]+月)/g, "")
        return newLunarcalendar === "初一" ? "lunarfirst" : ""
    }
}

const holiday = (day) => {
    const info = calendarInfo[day.date.format("YYYY-MM-DD")] || {}
    return info.type === 2 ? "假" : info.type === 0 && (info.weekday === 6 || info.weekday === 7) ? "班" : ""
}

const getHolidayClass = (day) => {
    const info = calendarInfo[day.date.format("YYYY-MM-DD")] || {}
    return info.type === 2 ? "holiday h-day" : info.type === 0 && (info.weekday === 6 || info.weekday === 7) ? "extra-work-day h-day" : ""
}

onMounted(() => {
    getCalendar(date.getFullYear())
    getCalendarEvent()
    change(date)
})
</script>


<style scoped>
:deep(.calendar) {
    background: rgba(255, 255, 255, .8);
}

:deep(.calendar-detail) {
    background: rgba(255, 255, 255, .8);
    height: 100%;
}

:deep(.special-day) {
    background: #9d9d9d;
}

:deep(.holiday) {
    background: rgb(148 211 51 / 70%);
    color: #545454;
}

:deep(.h-day) {
    position: absolute;
    top: 5px;
    right: 5px;
    border-radius: 50%;
    width: 20px;
    height: 20px;
    padding: 5px;
}

:deep(.notCurrentMonth .h-day) {
    opacity: .3;
}

:deep(.extra-work-day) {
    background: rgb(255 0 0 / 70%);
    color: aliceblue;
}

:deep(.el-scrollbar__bar.is-vertical) {
    display: none;
}

:deep(.calendar-row) {
    display: flex;
    flex-wrap: wrap;
}

:deep(.calendar-item) {
    width: calc(25% - 24px);
    padding: 10px;
    margin: 2px;
    min-width: 50px;
    background: rgba(0, 0, 0, .1);
    border-radius: var(--border-radius);
    text-align: center;
    display: flex;
    align-items: center;
    justify-content: center;
}

:deep(.calendar-item2) {
    width: calc(50% - 8px);
    min-width: 50px;
    background: rgba(0, 0, 0, .1);
    border-radius: var(--border-radius);
    text-align: center;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 2px;
    margin-top: 2px;
}

:deep(.calendar-item2 + .calendar-item2) {
    margin-left: 5px;
}

:deep(.solarterms) {
    color: #0035ffde;
}

:deep(.lunarfirst) {
    color: red;
}

:deep(.notCurrentMonth .lunarfirst),
:deep(.notCurrentMonth .lunarfestival),
:deep(.notCurrentMonth .solarfestival),
:deep(.notCurrentMonth .solarterms) {
    opacity: .5;
}

:deep(.lunarfestival) {
    color: #c30000;
}

:deep(.solarfestival) {
    color: #8911afd6;
}

:deep(.empty-event) {
    height: 100%;
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
}

:deep(.el-form-item__error) {
    top: 26%;
    right: 25px;
    left: unset;
    font-size: calc(var(--font-size) - 4px);
}

:deep(.event-item-inner) {
    padding: 5px 10px;
    margin: 3px;
    display: flex;
    width: 100%;
    background: rgba(129, 129, 129, .4);
    border-radius: var(--border-radius);
    height: calc(var(--font-size) * 2 + 10px);
    align-items: center;
}

:deep(.show-event-item) {
    background: #42c900;
    width: var(--font-size);
    aspect-ratio: 1;
    position: absolute;
    top: 4px;
    left: 4px;
    border-radius: 50%;
}

:deep(.selected .show-event-item) {
    background: #4de700;
}
</style>

<style lang="scss">
.time-picker {
    inset: 44px auto auto 0px !important;
    width: calc(100% - 3px);

    .el-time-panel {
        width: 100%;
    }
}

.calendar-dialog .el-dialog__body {
    padding: 0;
}

.calendar-dialog .el-dialog__footer {
    padding: 0 10px 10px 10px;
}
</style>